import 'dart:convert';

import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/services/api.dart';

import '../../../helper.dart';
import '../../../router.dart';
import 'state.dart';

class LocalLifeLogic extends GetxController {
  final state = LocalLifeState();

  @override
  void onInit() {
    super.onInit();

    state.titleString = '';
    var locationJson = SpUtil.getObject(Config.USER_CURRENT_LOCATION); // 获取定位信息
    // String adCode ='';
    // if (locationJson != null && locationJson.isNotEmpty) {
    //   Map<String, dynamic> params;
    //   if (locationJson['userSelectAddress'] == null ||
    //       locationJson['userSelectAddress'].length == 0) {
    //     adCode = locationJson['AMapResult']['adCode'];
    //   } else {
    //     adCode = locationJson['userSelectAddress']['city_num_id']
    //         ?.toString() ??
    //         (locationJson['userSelectAddress']['city_code']?.toString() ?? '0');
    //   }
    // }
    //  Permission.location.status.then((value) {
    //    if (value != PermissionStatus.granted || locationJson == null || locationJson.isEmpty || adCode=='' || adCode==null ) {
    //      state.tips = '未获取到位置信息，请至首页获取位置信息后重试';
    //      update();
    //    }
    //    else{
    //      state.tips = '';
    //      update();
    //    }
    //  });

  }

  @override
  void onReady() {
    super.onReady();

    var locationJson = SpUtil.getObject(Config.USER_CURRENT_LOCATION); // 获取定位信息
    if (locationJson != null && locationJson.isNotEmpty) {
      Map<String, dynamic> params;
      if (locationJson['userSelectAddress'] == null ||
          locationJson['userSelectAddress'].length == 0) {
        String adCode = locationJson['AMapResult']['adCode'];
        if((adCode==null)||(adCode.isEmpty))
          {
            adCode='0';
          }
        else {
          adCode = adCode.substring(0, adCode.length - 2) + '00';
        }
        params = {
          'data_sign': 0,
          'channel_num_id': 99,
          'use_platform': 2,
          'maplocation_x': locationJson['AMapResult']['longitude'],
          'maplocation_y': locationJson['AMapResult']['latitude'],
          'city_num_id': adCode,
        };
      } else {
        String adCode = locationJson['userSelectAddress']['city_num_id']
                ?.toString() ??
            (locationJson['userSelectAddress']['city_code']?.toString() ?? '0');
        if(adCode.length>=6)
          {
            adCode = adCode.substring(0, adCode.length - 2) + '00';
          }
        params = {
          'data_sign': 0,
          'channel_num_id': 99,
          'use_platform': 2,
          'maplocation_x': locationJson['userSelectAddress']['maplocation_x'],
          'maplocation_y': locationJson['userSelectAddress']['maplocation_y'],
          'city_num_id': adCode,
        };
      }
      Api.cityShopList(params).listen((event) {
        // print('========cityShopList======== event = $event');
        if (event['code'] == 0) {
          state.shopInfosList = event['ec_sub_shop_infos'];
        }
        update();
      });
    }

    var params = {
      'from_sign': 1, //死值,移动端专用
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'tmpl_num_id': Get.arguments['model']['linktarget'] ?? '', //模板ID
      // 'ec_shop_num_id': SpUtil.getInt('storeShopNum'), //店铺ID
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
    }; // channelPageTemplate
    Api.channelPageTemplate(params).listen((event) {
      print(' ===== 频道页模板详情：=====   event = $event');
      if (event['code'] == 0) {
        state.titleString = event['instance']['tmpl_title'];
        List list = event['instance']['data'];
        if (event['instance']['data'] != null) {
          // List list1 = [];
          // for (int i = 0; i < list.length; i++) {
          //   var map = list[i];
          //   if (map['widgets_data_status'] == 1) {
          //     list1.add(map);
          //   }
          // }
          state.templateList = jsonDecode(
              event['instance']['data'][0]['widgets_data_params'])['pictures'];
          // processingList();
          print("state.templateList=${state.templateList}");
        } else {
          state.templateList = [];
        }
      }
      update();
    });
// <<<<<<< HEAD
//     // var params1 = {
//     //   'from_sign': 1,  //死值,移动端专用
//     //   'data_sign': 0,
//     //   'channel_num_id': '99',
//     //   'use_platform': 2,
//     //   'tmpl_num_id': '21081300050001', //模板ID
//     //   // 'tmpl_num_id': Get.arguments['model']['linktarget'] ?? '', //模板ID
//     //   'ec_shop_num_id': SpUtil.getInt('storeShopNum'), //店铺ID
//     // };
//     // Api.channelPageTemplate(params1).listen((event) {
//     //   // print(' ===== 频道页模板详情：=====   event = $event');
//     //   if (event['code'] == 0) {
//     //     state.titleString = event['instance']['tmpl_title'];
//     //     List list = event['instance']['data'];
//     //     if (event['instance']['data'] != null) {
//     //       List list1 = [];
//     //       for (int i = 0; i < list.length; i ++) {
//     //         var map = list[i];
//     //         if (map['widgets_data_status'] == 1) {
//     //           list1.add(map);
//     //         }
//     //       }
//     //       state.templateList = list1;
//     //     } else {
//     //       state.templateList = [];
//     //     }
//     //   }
//     //   update();
//     // });
// =======
//     var params1 = {
//       'from_sign': 1, //死值,移动端专用
//       'data_sign': 0,
//       'channel_num_id': '99',
//       'use_platform': 2,
//       'tmpl_num_id': '21081300050001', //模板ID
//       // 'ec_shop_num_id': SpUtil.getInt('storeShopNum'), //店铺ID
//       "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
//     };
//     Api.channelPageTemplate(params1).listen((event) {
//       // print(' ===== 频道页模板详情：=====   event = $event');
//       if (event['code'] == 0) {
//         state.titleString = event['instance']['tmpl_title'];
//         List list = event['instance']['data'];
//         if (event['instance']['data'] != null) {
//           List list1 = [];
//           for (int i = 0; i < list.length; i++) {
//             var map = list[i];
//             if (map['widgets_data_status'] == 1) {
//               list1.add(map);
//             }
//           }
//           state.templateList = list1;
//         } else {
//           state.templateList = [];
//         }
//       }
//       update();
//     });
  }

  void getAndGoThirdShop(int shopId) {
    var params = {
      "data_sign": 0,
      "channel_num_id": 99,
      "use_platform": 2,
      "access_token": SpUtil.getString("token"),
      "ec_shop_num_id": shopId.toString(),
    };
    Api.getShopInfo(params).listen((event) {
      if (event != null && event['code'] == 0) {
        if (event['ec_shop_infos'].length > 0) {
          SpUtil.remove(Config.GET_SHOP_INFO);
          var shoplistes = event['ec_shop_infos'];
          SpUtil.putObject(Config.GET_SHOP_INFO, {
            'shop_name': shoplistes[0]['ec_shop_name'],
            'shop_id': shoplistes[0]['ec_shop_num_id'],
            'super_ec_shop_num_id': shoplistes[0]['super_ec_shop_num_id'],
            'is_get_home': shoplistes[0]['is_get_home'],
            'is_express': shoplistes[0]['is_express'],
            'service_telphone': shoplistes[0]['service_telphone'],
            'is_pick_up': shoplistes[0]['is_pick_up'],
            'adr': shoplistes[0]['adr'],
            'telphone': shoplistes[0]['telphone'],
            'pickAdrId': shoplistes[0]['sub_unit_num_id'],
            'offShopName': shoplistes[0]['sub_unit_name'],
            'offShopadr': shoplistes[0]['sub_unit_adr'],
            'sub_unit_num_id': shoplistes[0]['sub_unit_num_id'],
            'isSupporySacn': true,
            'free_start_time': '1970-01-01' + shoplistes[0]['free_start_time'],
            'is_express_shops':
                shoplistes[0]['cloud_ec_shop_num_id'] == 1 ? true : false,
            'prv_num_id': shoplistes[0]['prv_num_id'],
            'prv_name': shoplistes[0]['prv_name'],
            'city_num_id': shoplistes[0]['city_num_id'],
            'city_name': shoplistes[0]['city_name'],
            'city_area_num_id': shoplistes[0]['city_area_num_id'],
            'city_area_name': shoplistes[0]['city_area_name'],
            'ec_shop_logo': shoplistes[0]['ec_shop_logo']
          });
          SpUtil.putInt(Config.IS_CHANGE_SHOP,
              SpUtil.getInt('storeShopNum') == shopId ? 0 : 1);
          Get.offAllNamed(RouteConfig.main, arguments: {'isChangeShop': true});
        }
      } else {
        if (event == null) return;
        toast(event['massage']);
      }
    });
  }
}
